<template>
  <el-dialog top="80px"
    :visible.sync="isVisible"
    :title="title"
    :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-container>
      <el-main v-loading="submitLoading"
        :style="{ 'max-height': maxHeightDialog }"
        :element-loading-text="submitLoading ? '提交中...' : '加载中...'"
        class="container-main">
        <el-form ref="elForm"
          size="small"
          label-position="right"
          :model="form"
          :rules="rules"
          label-width="120px">
          <div>
            <el-card shadow="never"
              style=" min-height: 450px;border-width: 0px;">
              <div>
                <div style="font-weight: bold;margin-bottom: 10px;">
                  基础信息
                </div>
                <div
                  style="background: rgb(250, 250, 250);border: 1px solid rgb(230, 235, 245);padding: 10px 0px;">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="所属网格"
                        prop="gridMount">
                        <treeselect v-model="form.gridMount"
                          placeholder="选择所属网格"
                          :options="gridTreeDataList"
                          :default-expand-level="Infinity"
                          style="width: 100%;"
                          @select="onGridSelect">
                          <div slot="value-label"
                            slot-scope="{ node }">
                            {{ node.raw.fullPathText }}
                          </div>
                        </treeselect>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="控制设备"
                        prop="deviceName">
                        <el-input v-model="form.deviceName"
                          placeholder="输入控制设备"
                          clearable />
                      </el-form-item>
                    </el-col>
                    <el-col :span="11">
                      <el-form-item label="编号"
                        prop="deviceCode">
                        <el-input v-model="form.deviceCode"
                          placeholder="输入编号"
                          clearable />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="设备类型"
                        prop="controlType">
                        <el-select v-model="form.controlType"
                          popper-class="global-select"
                          placeholder="选择设备类型"
                          clearable
                          filterable>
                          <el-option v-for="item in controlTypeList"
                            :key="item.dictValue"
                            :label="item.dictText"
                            :value="item.dictValue" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="11">
                      <el-form-item label="厂家"
                        prop="factory">
                        <el-input v-model="form.factory"
                          placeholder="输入厂家"
                          clearable />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="安装时间"
                        prop="installTime">
                        <el-date-picker v-model="form.installTime"
                          type="date"
                          placeholder="选择安装时间" />
                      </el-form-item>
                    </el-col>
                    <el-col :span="11">
                      <el-form-item label="安装位置"
                        prop="installSite">
                        <el-input v-model="form.installSite"
                          placeholder="输入安装位置"
                          clearable />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>

              </div>
              <div style="margin-top: 20px;">
                <div style="font-weight: bold;margin-bottom: 10px;">
                  绑定设备
                </div>
                <div>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="设备编码"
                        prop="deviceCode">
                        <el-input v-model="deviceCode"
                          placeholder="输入设备编码"
                          clearable />
                        <el-alert :title="message"
                          type="warning"
                          show-icon
                          :closable="false"
                          v-if="message != ''">
                        </el-alert>
                      </el-form-item>

                    </el-col>
                    <el-col :span="11">
                      <el-form-item style="margin-left:-110px">
                        <el-button size="small"
                          type="primary"
                          @click="toAdd()"
                          style="padding: 7px 20px;">
                          添加
                        </el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row style="margin-top:10px;">
                    <el-col :span="24">
                      <el-table ref="elTable"
                        border
                        fit
                        size="medium "
                        :data="dataList"
                        style="width: 100%">
                        <af-table-column align="center"
                          label="设备编码"
                          prop="deviceCode" />
                        <af-table-column align="center"
                          label="设备名称"
                          prop="deviceName" />
                        <af-table-column align="center"
                          label="设备型号"
                          prop="deviceModel" />
                        <af-table-column align="center"
                          label="设备功能"
                          prop="identifier"
                          width="300px">
                          <template slot-scope="{ row }">
                            <el-select v-model="row.identifier"
                              popper-class="global-select"
                              placeholder="选择设备功能"
                              clearable
                              filterable
                              size="mini">
                              <el-option v-for="item in row.tslOption"
                                :key="item.identifier"
                                :label="item.name"
                                :value="item.identifier" />
                            </el-select>
                          </template>
                        </af-table-column>
                        <af-table-column align="center"
                          label="操作区"
                          width="80px">
                          <template slot-scope="{ row }">
                            <el-popconfirm :title="'确定要删除吗？'"
                              placement="top"
                              @confirm="toDelete(row, $index, '确定')"
                              @cancel="toDelete(row, $index, '取消')">
                              <span class="text-delete-btn"
                                style="color:#409eff"
                                slot="reference">删除</span>
                            </el-popconfirm>

                          </template>
                        </af-table-column>
                      </el-table>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-card>
          </div>
        </el-form>

      </el-main>

      <el-footer>
        <el-button size="medium"
          icon="el-icon-close"
          :disabled="submitLoading"
          style="width: 120px; margin-right: 10px"
          @click="isVisible = false">
          取消
        </el-button>
        <el-button size="medium"
          type="primary"
          icon="el-icon-check"
          :disabled="submitLoading"
          :loading="submitLoading"
          style="width: 120px"
          @click="toSubmit">
          {{ params.item.id == -1 ? "提交" : "修改" }}
        </el-button>
      </el-footer>
    </el-container>

  </el-dialog>
</template>
<script>
import dataFormMixins from "@/mixins/data-form-mixins";
import deviceManageApi from "@/api/device-manage";
import remoteControlApi from "@/api/remote-control";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "RemoteControlAdd",
  components: {
    Treeselect,
  },
  mixins: [dataFormMixins],
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    params: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data () {
    return {
      controlTypeList: [],
      gridTreeDataList: [],
      deviceCode: '',
      dataList: [],
      message: ''
    };
  },
  computed: {
    isVisible: {
      get () {
        return this.dialogVisible;
      },
      set () {
        this.toClose();
      }
    },
  },

  created () { },
  mounted () {
    this.form = {
      id: null,
      deviceName: "", // 控制设备
      deviceCode: '', //编号
      controlType: null, // 控制类型
      factory: '', // 厂家
      installTime: '', // 安装时间
      installSite: '', // 安装位置
      gridMount: null, // 所属网格
      itemList: []
    }
    this.rules = {
      deviceName: this.getValidatorForm(),
      controlType: this.getValidatorForm("change"),
    }

    this.getSelectData()

    if (this.params.item.id !== -1) {
      this.getDetail();
    }
  },
  methods: {
    getSelectData () {
      deviceManageApi.getDictValueAttr({
        fieldName: "control_model",
        tableName: "t_equipment_control"
      }).then(ret => {
        this.controlTypeList = ret.data.dictValue;
      });

      deviceManageApi
        .getGridTree()
        .then(ret => {
          this.gridTreeDataList = ret.data.data.rows;
        })
        .catch(() => {
          this.gridTreeDataList = [];
        });
    },
    onGridSelect (node, instanceId) {
      // this.form.gridMountFullPath = node.fullPath;
      // this.form.gridMountFullPathText = node.fullPathText
      //   ? node.fullPathText
      //   : "";
    },

    getDetail () {
      remoteControlApi.getControlDeviceInfo({
        id: this.params.item.id
      }).then(ret => {
        this.detailObj = ret.data.data;
        this.form = { ...this.detailObj };
        this.detailObj.itemList.forEach((ele) => {
          ele.tslOption = ele.tsl ? JSON.parse(ele.tsl) : []
        })
        this.dataList = this.detailObj.itemList
      })
    },
    toAdd () {
      remoteControlApi.checkControlDevice({
        equipmentCode: this.deviceCode,
        controlDeviceId: this.params.item.id != -1 ? this.params.item.id : ''
      }).then((res) => {
        this.message = ''
        res.data.data.tslOption = res.data.data.tsl ? JSON.parse(res.data.data.tsl) : []
        this.dataList.push(res.data.data)

      }).catch((e) => {
        this.message = '该设备已绑定'
      })
    },
    getDataList () {
      const dataList = [
        {
          deviceCode: '003M20222022011VN22110059',
          deviceName: '306插座0059',
          deviceModel: '智能用电监测模EMR1501',
          deviceFunction: '开关控制'
        },
        {
          deviceCode: '003M20222022011VN22110059',
          deviceName: '306插座0059',
          deviceModel: '智能用电监测模EMR1501',
          deviceFunction: '亮度调节'
        },
        {
          deviceCode: '003M20222022011VN22110059',
          deviceName: '306插座0059',
          deviceModel: '智能用电监测模EMR1501',
          deviceFunction: '温度调节'
        },
        {
          deviceCode: 'AJ20100759',
          deviceName: 'SMR3002组合式电气火灾探测器',
          deviceModel: '智能预警监测主机（有电弧NB）SMR3002-ENA',
          deviceFunction: '开关控制'
        },
        {
          deviceCode: 'AJ20100759',
          deviceName: 'SMR3002组合式电气火灾探测器',
          deviceModel: '智能预警监测主机（有电弧NB）SMR3002-ENA',
          deviceFunction: '湿度调节'
        },
        {
          deviceCode: 'AJ20100759',
          deviceName: 'SMR3002组合式电气火灾探测器',
          deviceModel: '智能预警监测主机（有电弧NB）SMR3002-ENA',
          deviceFunction: '亮度调节'
        },
        {
          deviceCode: 'AJ20100759',
          deviceName: 'SMR3002组合式电气火灾探测器',
          deviceModel: '智能预警监测主机（有电弧NB）SMR3002-ENA',
          deviceFunction: '温度调节'
        },
        {
          deviceCode: '003M20222022011VN22110022',
          deviceName: '302插座0022',
          deviceModel: '智能用电监测模EMR1501',
          deviceFunction: '开关控制'
        },
        {
          deviceCode: '003M20222022011VN22110022',
          deviceName: '302插座0022',
          deviceModel: '智能用电监测模EMR1501',
          deviceFunction: '温度调节'
        },
        {
          deviceCode: 'SJ22030156',
          deviceName: 'EMR1002智能预警监测主机',
          deviceModel: '智能预警监测主机（增强NB版）EMR1002-INAS',
          deviceFunction: '开关控制'
        },
        ,
        {
          deviceCode: 'SJ22030156',
          deviceName: 'EMR1002智能预警监测主机',
          deviceModel: '智能预警监测主机（增强NB版）EMR1002-INAS',
          deviceFunction: '亮度调节'
        },
      ]

      const list = []
      dataList.forEach((ele) => {
        if (!list.find(e => e.deviceCode == ele.deviceCode)) {
          list.push({
            deviceCode: ele.deviceCode,
            itemList: []
          })
        }
      })

      list.forEach((ele) => {
        this.dataList.forEach((e) => {
          if (ele.deviceCode == e.deviceCode) {
            ele.itemList.push(e)
          }
        })
      })
    },
    toDelete (data, index, type) {
      if (type === "确定") {
        this.dataList.splice(index, 1)
      }
    },
    toClose () {
      this.$emit("close");
    },
    toSubmit () {
      this.$refs.elForm.validate(valid => {
        if (valid) {
          this.submitLoading = true

          const itemList = []
          this.dataList.forEach((ele) => {
            itemList.push({
              equipmentId: ele.equipmentId,
              identifier: ele.identifier
            })
          })

          const model = {};
          Object.keys(this.form).forEach((key) => {
            model[key] = this.form[key]
          })
          model.itemList = itemList

          model.installTime = this.$moment(new Date(model.installTime)).format(
            'YYYY-MM-DD HH:mm:ss'
          )
          remoteControlApi.addControlDevice(model).then(ret => {
            this.submitLoading = false;
            this.isVisible = false;
            this.$message({
              message: "提交成功！",
              type: "success"
            });
            const obj = this.controlTypeList.filter((e) => {
              return model.controlType == e.dictValue
            })
            let controlTypeStr = ''
            if (obj.length > 0) {
              controlTypeStr = obj[0].dictText
            }
            this.$emit("submit", controlTypeStr);
          })
            .catch(() => {
              this.submitLoading = false;
            });

        } else {
          this.$message({
            message: "请完善表单内容！",
            type: "warning",
            duration: 4000
          });
          return false;
        }
      });
    },
  }
};
</script>

<style lang="scss" scoped>
@import "../../../../../styles/part-custom";

/deep/.el-alert--warning.is-light {
  padding: 0px 16px;
  width: 97%;
  margin-left: 0px;
  font-size: 12px;
  margin: 5px 0px;
  border: 1px solid #ffe58f;
  height: 28px;
}

/deep/.el-input--mini .el-input__inner {
  height: 26px;
  line-height: 26px;
}

.text-delete-btn {
  color: #409eff;
  cursor: pointer;
}
</style>
